package com.atguigu.tingshu.user.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.LastUserListenPlayVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private KafkaService kafkaService;


    @Override
    public void updateListenProcess(UserListenProcessVo userListenProcessVo) {
        //获取当前登录对象的ID
        Long userId = AuthContextHolder.getUserId();
        //创建集合的名称
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        //构建查询条件
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("albumId").is(userListenProcessVo.getAlbumId())
                .and("trackId").is(userListenProcessVo.getTrackId()));
        //执行查询
        UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        if (listenProcess == null) {
            //把数据保存到mongodb中
            listenProcess = new UserListenProcess();
            listenProcess.setUserId(userId);
            listenProcess.setAlbumId(userListenProcessVo.getAlbumId());
            listenProcess.setTrackId(userListenProcessVo.getTrackId());
            listenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            listenProcess.setIsShow(1);
            listenProcess.setCreateTime(new Date());
            listenProcess.setUpdateTime(new Date());
            mongoTemplate.save(listenProcess, collectionName);
        } else {
            // 更新声音进度
            listenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            listenProcess.setUpdateTime(new Date());
            mongoTemplate.save(listenProcess, collectionName);
        }

        // 判断当前声音该用户在当天有没有播放过
        String redisKey = "track:paly" + userListenProcessVo.getTrackId() + ":" + DateUtil.format(new Date(), "yyyy-MM-dd") + ":" + userId;
        Boolean hasKey = redisTemplate.hasKey(redisKey);
        if (!hasKey) {
            //向kafka中发送更新声音播放记录的消息
            TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
            trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replace("-", ""));
            trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
            trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
            trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
            trackStatMqVo.setCount(1);
            kafkaService.sendMsg(KafkaConstant.QUEUE_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));

            //在redis中存储播放记录
            redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(listenProcess), 1, TimeUnit.DAYS);

        }


    }

    @Override
    public BigDecimal getTrackBreakSecond(Long trackId) {
        //获取当前登录对象的ID
        Long userId = AuthContextHolder.getUserId();
        //根据用户Id,声音Id获取播放进度对象
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("trackId").is(trackId));
        //查询的表名
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
        if (userListenProcess != null) {
            return userListenProcess.getBreakSecond();
        }
        return new BigDecimal(0);
    }

    @Override
    public LastUserListenPlayVo getLatelyTrack() {
        //获取当前登录对象的ID
        Long userId = AuthContextHolder.getUserId();
        //查询mongoDB中数据
        UserListenProcess mongoTemplateOne = mongoTemplate.findOne(new Query().addCriteria(Criteria.where("userId").is(userId)).limit(1).with(Sort.by(Sort.Direction.DESC, "updateTime")),
                UserListenProcess.class,
                MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
        LastUserListenPlayVo lastUserListenPlayVo = new LastUserListenPlayVo();
        //判断如果为空，则默认返回48237专辑和1429声音
        if(lastUserListenPlayVo == null){
            lastUserListenPlayVo.setAlbumId(48237L);
            lastUserListenPlayVo.setTrackId(1429L);
        }else{ //如果不为空，则返回该对象
            lastUserListenPlayVo.setAlbumId(mongoTemplateOne.getAlbumId());
            lastUserListenPlayVo.setTrackId(mongoTemplateOne.getTrackId());
        }

        return lastUserListenPlayVo;
    }
}
